package com.jinzhuo;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class hello_consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2、设置参数
        factory.setHost("localhost"); //ip 默认主机名
        factory.setPort(5672);  //默认5672
        factory.setVirtualHost("/jinzhuo"); //设置虚拟机端口 默认/
        factory.setUsername("jinzhuo"); //默认guest
        factory.setPassword("jinzhuo"); //默认guest
        //3、创建链接
        Connection connection = factory.newConnection();
        //4、创建channel
        Channel channel = connection.createChannel();

        //5、生命队列（可以不生明，发送者已经申明队列）

        //6、接受消息
        /**
         * basicConsume(String var1, boolean var2, Consumer var3)
         * 参数
         *  var1 队列名称
         *  var2 是否自动确认
         *  var3 回调对象
         */
        Consumer consumer = new DefaultConsumer(channel){
            /**
             * 回调方法
             * @param consumerTag 标识
             * @param envelope 获取一些信息，交换机，路由
             * @param properties 配置信息
             * @param body 数据
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                super.handleDelivery(consumerTag, envelope, properties, body);
                System.out.println(
                 "consumerTag:"+consumerTag+
                 "envelope:"+envelope.getRoutingKey()+
                 "properties:"+properties+
                 "body:"+new String(body)
                );
            }
        };
        channel.basicConsume("rabbitmq",true,consumer);
        //TODO 消费者不要关闭连接
    }
}
